package com.alibaba.serverless;

import com.alibaba.serverless.common.ApiGwRequest;
import com.alibaba.serverless.common.ApiGwResponse;
import com.alibaba.serverless.domain.ReceiveParams;
import com.alibaba.serverless.service.SmtpService;
import com.alibaba.serverless.service.impl.ISmtpServiceImpl;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.FunctionComputeLogger;
import com.aliyun.fc.runtime.FunctionInitializer;
import com.aliyun.fc.runtime.PojoRequestHandler;

/**
 * @author mac_zyj
 */
public class MailHandle implements FunctionInitializer, PojoRequestHandler<ApiGwRequest, ApiGwResponse> {

    private SmtpService smtpService=new ISmtpServiceImpl();
    @Override
    public void initialize(Context context)  {
        FunctionComputeLogger logger = context.getLogger();
        logger.debug(String.format("RequestID is %s %n", context.getRequestId()));
    }

    @Override
    public ApiGwResponse handleRequest(ApiGwRequest apiGwRequest, Context context) {
        ApiGwResponse response = new ApiGwResponse();
        ReceiveParams receiveParams=(ReceiveParams)apiGwRequest. initQueryToClass(ReceiveParams.class);
        receiveParams.checkReceiveParams();
        try {
            smtpService.sendSingleApiMail(receiveParams);
            response.getHeaders().put("Content-type", "application/json; charset=utf-8");
            response.setBody("Ok");
            response.setStatusCode(200);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.getHeaders().put("Content-type", "text/html; charset=utf-8");
        response.setBody("FALSE");
        response.setStatusCode(500);
        return response;
    }
}
